/**
 * @description 博客的service层
 * @author 印明帝
 */

const { Blog,User,UserRelation } = require('../db/model/index')
const { formatBlogs,formatUser } = require('./_format')
/**
 * 创建博客
 * @method create
 * @param {Object} blogInfo 
 * @returns {Promise}
 */
async function create({ userId,content,image}) {
  let result = await Blog.create({
    userId,
    content,
    image
  }) 
  return result
}
/**
 * @member getBlogs
 * @param {Number} id 
 * @param {Number} index 
 */
async function getBlogs({id,index}) {
  
  //每页的数据条数
  let limit = 10 
  //当前偏移
  let offset = limit * index 
  // user表的查询条件
  let userWhereOpt = null
  // 如果id存在就查询带id的
  if(id) {
    userWhereOpt = {
      id: id
    }
  }
  // 连表查询
  let result = await Blog.findAndCountAll({
    limit,
    offset,
    order: [
      ['id','desc']
    ],
    include: [{ // include关键字表示关联查询
      model: User, // 指定关联的model
      attributes: ['id','nickName','picture'],
      where: userWhereOpt
    }]
  })
  // 格式化blog数据
  let formatData = formatBlogs(result)
  return formatData
}
/**
 * 获取关注的人的Blog
 * @method getFollowersBlogList
 * @param {Number} userId
 * @param {Number} index 
 */
async function getFollowersBlogList(userId,index = 0) {
  let limit = 10
  let offset = index * limit
  let result = await Blog.findAndCountAll({
    limit,
    offset,
    order: [
      ['id', 'desc']
    ],
    include: [
      {
        model: User,
        attributes: ['id', 'nickName', 'picture']
      },{
        model: UserRelation,
        attributes: ['userId', 'followerId'],
        where: {
          userId
        }
      }
    ]
  })
  // 格式化数据
  blogList = formatBlogs(result)
  return blogList
}

module.exports = {
  create,
  getBlogs,
  getFollowersBlogList
}